import os
import argparse

def search_replace_in_files(directory, search_str, replace_str, ext_filter=None, recursive=False):
    """
    在文件中搜索并替换文本
    :param directory: 目标目录
    :param search_str: 要搜索的字符串
    :param replace_str: 替换字符串
    :param ext_filter: 仅处理指定扩展名的文件，如'.txt'
    :param recursive: 是否递归处理子目录
    """
    file_count = 0
    replace_count = 0
    
    try:
        # 遍历目录
        for root, dirs, files in os.walk(directory):
            for file in files:
                # 过滤文件扩展名
                if ext_filter and not file.lower().endswith(ext_filter.lower()):
                    continue
                
                file_path = os.path.join(root, file)
                
                # 尝试以文本模式打开文件
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # 检查是否需要替换
                    if search_str in content:
                        new_content = content.replace(search_str, replace_str)
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(new_content)
                        
                        changes = content.count(search_str)
                        replace_count += changes
                        file_count += 1
                        print(f"已处理: {file_path} (替换 {changes} 处)")
                
                except UnicodeDecodeError:
                    print(f"跳过二进制文件: {file_path}")
                except Exception as e:
                    print(f"处理文件 {file_path} 时出错: {str(e)}")
            
            # 如果不递归处理子目录，只处理当前目录
            if not recursive:
                break
        
        print(f"\n完成！共处理 {file_count} 个文件，替换 {replace_count} 处内容")
        
    except Exception as e:
        print(f"发生错误: {str(e)}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='文本搜索替换脚本')
    parser.add_argument('directory', help='目标目录路径')
    parser.add_argument('search', help='要搜索的字符串')
    parser.add_argument('replace', help='替换字符串')
    parser.add_argument('--ext', help='文件扩展名过滤，如.txt')
    parser.add_argument('--recursive', action='store_true', help='递归处理子目录')
    
    args = parser.parse_args()
    
    search_replace_in_files(
        directory=args.directory,
        search_str=args.search,
        replace_str=args.replace,
        ext_filter=args.ext,
        recursive=args.recursive
    )
